<?php

namespace app\merchants\controller;

use app\common\libs\GetLatAndLon;
use app\common\validate\shop\ShopTagsValid;
use app\common\validate\shop\ShopValid;
use app\merchants\loader\Services;
use think\Exception;

/**
 * 门店管理
 */
class Shop extends ApiBase
{
    /**
     * 门店列表 分页
     */
    public function page()
    {
        try {
            $option = $this->makeShopWhere();
            $result = Services::Shop()->getPage($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 根据请求,生成条件
     * @return array
     */
    private function makeShopWhere(): array
    {
        $params = $this->request->get();
        $options = $this->formatOption($params);
        $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
        if (!empty($params['keyword'])) {
            $where[] = ['title|manager|mobile|code', 'like', "%" . trim($params['keyword']) . "%"];
        }
        // 标签ID
        if (!empty($params['tag_id'])) {
            $where['id'] = ['in', function ($query) use ($params) {
                $query->name('shop_tags_bind')->where('tags_id', $params['tag_id'])->field('shop_id');
            }];
        }
        if (!empty($this->adminUser['sub_admin_ids'])) {
            $where[] = ['op_user', 'in', $this->adminUser['sub_admin_ids']];
        }
        if (!empty($params['admin_id'])) {
            $where[] = ['op_user', '=',trim($params['admin_id'])];
        }
        $options['where'] = $where;
        return $options;
    }

    /**
     * 门店列表
     */
    public function list()
    {
        try {
            $option = $this->makeShopWhere();
//            $option['where'][] = ['status', '=' , '1'];
            $result = Services::Shop()->getList($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 编辑门店
     */
    public function save()
    {
        $params = $this->request->post();
        try {
            $params['mer_id'] = $this->adminUser['mer_id'];
            $scene = '.create';
            if (!empty($params['id'])) {
                $scene = '.edit';
            }
            $this->validate($params, ShopValid::class . $scene);
            $getIngAanLat = GetLatAndLon::getInstance()
                            ->setCity($params['city'])
                            ->setAddress($params['country'])
                            ->sendLatAanLon();
            if (!empty($getIngAanLat)){
                $params['lat'] = $getIngAanLat['lat'];
                $params['lng'] = $getIngAanLat['lng'];
            }
            $id = Services::Shop()->saveShop($params);
            api_result(API_SUCCESS, '保存成功', ['id' => $id]);
        } catch (Exception $e) {
            api_result($e);
        } catch (\JsonException $e) {
        }
    }

    /**
     * 门店状态修改
     */
    public function save_status():void
    {
        $params = $this->request->post();
        try {
            $this->validate($params, ShopValid::class . '.save_status');
            $whereData  = [
                'mer_id' => $this->adminUser['mer_id'],
                'id' => $params['id']
            ];
            $data =  ['status' => $params['status']];
            Services::Shop()->save_status($whereData ,$data);
            api_result(API_SUCCESS, '保存成功', ['id' => $params['id']]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 门店详情
     */
    public function info()
    {
        $id = $this->request->get('id');
        try {
            if (empty($id)) {
                api_exception(API_ERROR, '门店不能为空');
            }
            $option['where'] = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            $result = Services::Shop()->getInfo($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 删除门店
     */
    public function del()
    {
        $id = $this->request->post('id');
        try {
            if (empty($id)) {
                api_exception(API_ERROR, '门店不能为空');
            }
            $where = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            Services::Shop()->delShop($where);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 门店标签列表 分页
     */
    public function tags_page()
    {
        try {
            $options = $this->makeShopTagWhere();
            $result = Services::Shop()->getShopTagPage($options);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 根据请求,生成条件
     * @return array
     */
    private function makeShopTagWhere(): array
    {
        $params = $this->request->get();
        $options = $this->formatOption($params);
        $where[] = ['mer_id', '=', $this->adminUser['mer_id']];
        if (!empty($params['keyword'])) {
            $where[] = ['title', 'like', "%" . trim($params['keyword']) . "%"];
        }
        $options['where'] = $where;
        return $options;
    }

    /**
     * 门店标签列表
     */
    public function tags_list()
    {
        try {
            $options = $this->makeShopTagWhere();
            $result = Services::Shop()->getShopTagList($options);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 编辑门店标签
     */
    public function tags_save()
    {
        $params = $this->request->post();
        try {
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $scene = '.create';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, ShopTagsValid::class . $scene);
            $id = Services::Shop()->saveShopTag($params);
            api_result(API_SUCCESS, '保存成功', ['id' => $id]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 门店标签详情
     */
    public function tags_info()
    {
        $id = $this->request->get('id');
        try {
            if (empty($id)) {
                api_exception(API_ERROR, '门店标签ID不能为空');
            }
            $option['where'] = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            $result = Services::Shop()->getShopTagInfo($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 删除门店标签
     */
    public function tags_del()
    {
        $id = $this->request->post('id');
        try {
            if (empty($id)) {
                api_exception(API_ERROR, '标签ID不能为空');
            }
            $where = [['id', '=', $id], ['mer_id', '=', $this->adminUser['mer_id']]];
            Services::Shop()->delShopTags($where);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 标签绑定门店
     */
    public function tags_bind()
    {
        $params = $this->request->post();
        try {
            if (empty($params['tags_id'])) {
                api_exception(API_ERROR, '标签ID不能为空');
            }
            if (empty($params['shop_id'])) {
                api_exception(API_ERROR, '门店ID不能为空');
            }
            Services::Shop()->bindShopTags($params['tags_id'], $params['shop_id'], $this->merId);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }
}
